/*
 * 程序清单：这是一个 串口 设备使用例程
 * 例程导出了 uart_sample 命令到控制终端
 * 命令调用格式：uart_sample uart2
 * 命令解释：命令第二个参数是要使用的串口设备名称，为空则使用默认的串口设备
 * 程序功能：通过串口输出字符串"hello RT-Thread!"，然后错位输出输入的字符
*/

#include <rtthread.h>
#include <rtdevice.h>
#include <drv_common.h>
#include <string.h>

#define SAMPLE_UART_NAME       "uart2"

/* 用于接收消息的信号量 */
static struct rt_semaphore rx_sem;
static rt_device_t serial;

/* 接收数据回调函数 */
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    /* 串口接收到数据后产生中断，调用此回调函数，然后发送接收信号量 */
    rt_sem_release(&rx_sem);

    return RT_EOK;
}

static void serial_thread_entry(void *parameter)
{

    /* unworked */

    while (1)
    {
        // /* 从串口读取一个字节的数据，没有读取到则等待接收信号量 */
        // while (rt_device_read(serial, -1, &ch, 1) != 1)
        // {
        //     /* 阻塞等待接收信号量，等到信号量后再次读取数据 */
        //     rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
        // }
        // /* 读取到的数据通过串口错位输出 */
        // ch = ch + 1;
        // rt_device_write(serial, 0, &ch, 1);
        rt_thread_mdelay(5000);
    }
}

static int uart_sample(void)
{
    rt_err_t ret = RT_EOK;


    /* 查找系统中的串口设备 */
    serial = rt_device_find(SAMPLE_UART_NAME);
    if (!serial)
    {
        rt_kprintf("find %s failed!\n");
        return RT_ERROR;
    }

    /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(serial, RT_DEVICE_FLAG_RX_NON_BLOCKING | RT_DEVICE_FLAG_TX_BLOCKING);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial, uart_input);
    // /* 发送字符串 */
    // rt_device_write(serial, 0, str, (sizeof(str) - 1));

    /* 创建 serial 线程 */
    rt_thread_t thread = rt_thread_create("serial", serial_thread_entry, RT_NULL, 1024, 25, 10);
    /* 创建成功则启动线程 */
    if (thread != RT_NULL)
    {
        rt_thread_startup(thread);
    }
    else
    {
        ret = RT_ERROR;
    }

    return ret;
}
INIT_APP_EXPORT(uart_sample);

void swuart_calcCRC(rt_uint8_t* datagram, rt_uint8_t datagramLength)
{
    int i,j;

    rt_uint8_t* crc = datagram + (datagramLength-1); // CRC located in last byte of message
    rt_uint8_t currentByte;

    *crc = 0;
    
    // Execute for all bytes of a message
    for (i=0; i<(datagramLength-1); i++)
    { 
        currentByte = datagram[i]; // Retrieve a byte to be sent from Array
        for (j=0; j<8; j++)
        {
            if ((*crc >> 7) ^ (currentByte&0x01)) // update CRC based result of XOR operation
            {
                *crc = (*crc << 1) ^ 0x07;
            }
            else
            {
                *crc = (*crc << 1);
            }
            currentByte = currentByte >> 1;
        } // for CRC bit
    } // for message byte
    
    rt_kprintf("");
}


static void tmc_cmd(int argc, char *argv[])
{
    char ch;
    rt_err_t result;
    char tmc_tx_buffer[32] = {0x05, 0x00, 0x00, 0x48};
    rt_uint8_t length;

    // if (argc < 2)
    // {
    //     rt_kprintf("input invaild");
    //     return;
    // }

    if (!serial)
    {
        rt_kprintf("tmc device needs to be initialized first");
        return;
    }

    // if ((argv[1][0] != 'A') || (argv[1][1] != 'T'))
    // {
    //     rt_kprintf("tmc cmd input invaild");
    //     return;
    // }

    length = rt_strlen(tmc_tx_buffer);
    // rt_memcpy(tmc_tx_buffer, argv[1], length);

    // tmc_tx_buffer[length] = '\r';
    // tmc_tx_buffer[length + 1] = '\n';
    // tmc_tx_buffer[length + 2] = '\0';

    rt_device_write(serial, 0, tmc_tx_buffer, length);

    while (1)
    {
        /* 从串口读取一个字节的数据，没有读取到则等待接收信号量 */
        while (rt_device_read(serial, -1, &ch, 1) != 1)
        {
            /* 阻塞等待接收信号量，等到信号量后再次读取数据 */
            result = rt_sem_take(&rx_sem, 3000);
            if (result != RT_EOK)
            return;
        }
        rt_kprintf("%c", ch);
    }
}
MSH_CMD_EXPORT(tmc_cmd, tmc_cmd sample);
